<?php


namespace app\controller;

use app\BaseController;
use think\App;
use think\facade\Log;

define('TOKEN', 'meiribitui');

class Token extends BaseController
{
    /**
     * Category constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index()
    {
        if ($this->request->isPost()) {
            $data = $this->recMsg();
            Log::write(json_encode($data));
        } else {
            if ($this->request->param("signature") && $this->checkSignature()) {
                echo $this->request->param("signature");
                exit;
            }
        }
    }

    private function checkSignature(): bool
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 接收消息
     * @author Why
     * @return array $resArr 返回结果
     */
    public function recMsg(){
        //接收微信发送的XML数据包
        $postObj =  file_get_contents("php://input");

        //解析XML数据包为数组格式:SimpleXMLElement::__set_state(array())
        $postArr = simplexml_load_string($postObj, "SimpleXMLElement", LIBXML_NOCDATA);

        //获取数组中用户发送的内容
        $content = $postArr->Content;

        //将获取的内容转换为普通数组，方便以后的业务逻辑编写
        $jsonStr = json_encode($content);
        $resArr  = json_decode($jsonStr,true);

        return $resArr;
    }

}